﻿/* 
 * Project:  ImageVerification
 * Author :  ZofM (Gianni Marzaloni)
 * Site   :  http://www.zofm.net
 * Date   :  June 13th, 2006
 * 
 * This class provides istance methods for showing password image to the user.
 * Use it in your Forms to prevent spammers insertions.
 * 
 * For more information about this project contact me: info@zofm.net
 */

using System;
using System.Data;
using System.Text;
using System.Web;
using System.Drawing;
using System.Drawing.Text;
using System.Drawing.Imaging;
using System.Security.Cryptography;
using System.Drawing.Drawing2D;
using System.Web.UI;
using System.IO;
using System.Configuration;
using System.Collections.Generic;

namespace Portal.Admin.Screen.Render
{
    public class ImageVerification
    {
        //private string pathImageVerification = (string)System.Configuration.ConfigurationManager.AppSettings["CapchaImageLocation"];
        #region Private Properties

        /// <summary>
        /// Enumerate for the storing type of the passwords
        /// </summary>
        private enum StoreType
        {
            IpAddress, SessionID
        }

        //private StoreType _StoreType = StoreType.SessionID;
        private Color _BackColor = new Color();
        private Font _TextFont = new Font("Arial", 12);

        #endregion

        public ImageVerification()
        {
            _BackColor = Color.Black;
            // store type
        }

        /// <summary>
        /// Creates the image on the fly and save it in the output of httpcontext
        /// </summary>
        /// <param name="width">Width of the image</param>
        /// <param name="height">Height of the image</param>        
        public void ProcessRequest(int width, int height)
        {

            Bitmap bmp = new Bitmap(width, height);
            Graphics g = Graphics.FromImage(bmp);

            string randString = SetRandomPassword(6);
            HttpContext.Current.Session["codeImageVerifier"] = randString;
            
            g.FillRectangle(Brushes.Azure, 0, 0, width, height);
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.Default;
            g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;

            Random rand = new Random();
            for (int i = 0; i < randString.Length; i++)
            {
                Font drawFont = new Font("Arial", 13, FontStyle.Italic | (rand.Next() % 2 == 0 ? FontStyle.Bold : FontStyle.Regular));
                g.DrawString(randString.Substring(i, 1), drawFont, Brushes.Black, i * 35 + 10, rand.Next() % 12);
            }

            Point[] pt = new Point[10];
            for (int i = 0; i < 10; i++)
            {
                pt[i] = new Point(rand.Next() % 180, rand.Next() % 35);
                g.DrawEllipse(Pens.LightSteelBlue, pt[i].X, pt[i].Y, rand.Next() % 30 + 1, rand.Next() % 30 + 1);
            }

            string fileName = SetRandomPassword(32) +".jpg";
            HttpContext.Current.Session["fileNameCodeImageVerifier"] = fileName;
            string pathImageVerification = (string)System.Configuration.ConfigurationManager.AppSettings["CapchaImageLocation"];
            bmp.Save(pathImageVerification + fileName, System.Drawing.Imaging.ImageFormat.Jpeg);
            
            bmp.Dispose();
            g.Dispose();
        }




        /// <summary>
        /// Gets a generated random string
        /// </summary>
        /// <param name="size">Length of the string</param>
        /// <param name="lowerCase">If true, all the chars are in lowercase</param>
        public string SetRandomPassword(int size)
        {
            StringBuilder s = new StringBuilder();
            string strSource = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
            Random r = new Random();
            for (int i = 0; i < size; i++)
            {
                int characterIndex = Convert.ToInt32(r.Next(0, strSource.Length-1));
                //Generate the char and assign it to appendedChar
                char appendedChar = strSource[characterIndex];
                //Append appendedChar to randomString
                s.Append(appendedChar);
            }
            //return (lowerCase ? s.ToString().ToLower() : s.ToString());
            return (s.ToString());
            // storing the password in the DataSet
            //InsertCode((lowerCase ? s.ToString().ToLower() : s.ToString()));
        }
        #region Public Properties

        /// <summary>
        /// Gets or sets the background color of the image
        /// </summary>
        public Color BackColor
        {
            get
            {
                return _BackColor;
            }
            set
            {
                _BackColor = value;
            }
        }

        /// <summary>
        /// Gets or sets the font text
        /// </summary>
        public Font TextFont
        {
            get
            {
                return _TextFont;
            }
            set
            {
                _TextFont = value;
            }
        }
                
        public string checkCodeVerifier()
        {
            char[] stemp = new char[6];
            string strValue = HttpContext.Current.Session["codeImageVerifier"].ToString();

            for (int i = 0; i < strValue.Length; i++)
            {
                stemp[i] = strValue[i];
            }

            string strResult = "";
            for (int j = 0; j < stemp.Length; j++)
            {
                System.Threading.Thread.Sleep(100);
                strResult = strResult + stemp[j].ToString() + SetRandomPassword(5);
            }

            HttpContext.Current.Session.Remove("codeImageVerifier");
            return strResult;
        }
        #endregion
    }
}
